import path from "path";
import { DistStruct } from "../../../common/src/CreateDist";
import fs from "fs";
import * as cheerio from "cheerio";

export class LoadDev {
  dist: DistStruct;
  indexPath: string;
  constructor(dist: DistStruct) {
    this.dist = dist;
    // this.loadCss();
    // this.loadJs();
    this.indexPath = path.join(this.dist.getRootPath(), "index.html");
    const node = this.getIndex();
    const head = node("head");
    const v1 = !node("#devCss").length, v2 = !node("#devJs").length

    v1 &&
      this.quoteLayuiCss(head);

    v2 &&
      this.quoteLayuiJs(head);

    if (v1 || v2)
      this.writeBack(node);

    if (!node("#devJsManual").length)
      this.addDevJs();
  }
  private writeBack(node: cheerio.Root) {
    fs.writeFileSync(this.indexPath, node.html());
  }
  public getIndex() {
    return cheerio.load(fs.readFileSync(this.indexPath).toString());
  }
  private quoteLayuiJs(node: cheerio.Cheerio) {
    node.append(`<script src='dev/layui/layui.js' id='devJs'></script>`);
  }
  private quoteLayuiCss(node: cheerio.Cheerio) {
    node.append(`<link href='dev/layui/css/layui.css'  rel="stylesheet" id='devCss' />`);
  }
  private addDevJs() {
    const indexStr = fs.readFileSync(this.indexPath).toString();
    const $ = cheerio.load(indexStr);
    $("body").append(`<script src="dev/dev.js" id='devJsManual'></script>`);

    fs.writeFileSync(this.indexPath, $.html());
  }
}
